package com.atom.test.opengl.utils;

import android.content.res.Resources;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ShaderManager {
    final static String[][] shaderName = {
            {"jbullet_java/vertex.sh", "jbullet_java/frag.sh"},
            {"jbullet_java/vertex_color.sh", "jbullet_java/frag_color.sh"}
    };
    final static Map<String , Shader> maps = new HashMap<>() ;
    static Resources resources ;
    public static void loadDefalutShader(Resources r) {
        resources = r ;
        for (int i = 0; i < shaderName.length; i++) {
            String vertexPath = shaderName[i][0] ;
            String fragmentPath = shaderName[i][1] ;
            maps.put(vertexPath , createShader(vertexPath , fragmentPath , r)) ;
        }
    }
    public static void compileDefalutShader(){
        Set<Map.Entry<String, Shader>> entries = maps.entrySet();
        for (Map.Entry<String, Shader> entry:entries
             ) {
            entry.getValue().run() ;
        }
    }

    private static Shader createShader(String vertex , String frag , Resources res){
        return new Shader(vertex, frag).setResources(res) ;
    }

    public static int getTextureShaderProgram() {
        return getShaderProgram(shaderName[0][0] ,  shaderName[0][1]);
    }

    public static int getObjectShaderProgram() {
        return getShaderProgram(shaderName[1][0] ,  shaderName[1][1]);
    }

    public static int getShaderProgram(String vertex , String frag) {
        Shader shader = maps.get(vertex);
        if(shader == null){
            shader = new Shader(vertex,frag).setResources(resources) ;
            shader.run() ;
            maps.put(vertex , shader) ;
        }
        return shader.getProgram();
    }

    static  class  Shader {
        String vertex;
        String fragment;
        boolean isPath;
        boolean isRun = false ;
        int program;

        public Shader(String vertex, String fragment) {
            this(vertex, fragment, true);
        }

        public Shader(String vertex, String fragment, boolean isPath) {
            this.vertex = vertex;
            this.fragment = fragment;
            this.isPath = isPath;
        }

        public Shader setResources(Resources resources) {
            Log.e("intShader" , "vertex > "+vertex) ;
            if (isPath) {
                vertex = ShaderUtil.loadFromAssetsFile(vertex, resources);
                fragment = ShaderUtil.loadFromAssetsFile(fragment, resources);
                isPath = false ;
            }
            return this ;
        }

        public Shader run() {
            program = ShaderUtil.createProgram(vertex , fragment) ;
            Log.e("intShader" , "program > "+program) ;
            isRun = true ;
            return this ;
        }

        public int getProgram() {
            if(!isRun) return -1 ;
            return program;
        }
    }
}
